const BaseController = require("./base");

class Controller extends BaseController {
	constructor(...args) {
		super(...args);
		this.table = "menu";
		this.createRule = {
			name: "string",
			pid: "string",
			path: "string"
		};
		this.updateRule = this.createRule;
	}

	async index() {
		const { ctx, service } = this;
		const { pageNum, pageSize, ...where } = ctx.query;

		const res = await service.menu.list(
			isNaN(pageNum) ? 1 : parseInt(pageNum),
			isNaN(pageSize) ? 10 : parseInt(pageSize),
			where
		);

		const parent = res.data.parent;
		const children = res.data.children;
		const rootMenu = [];
		const map = {};
		parent.forEach((item) => {
			item.children = [];
			rootMenu.push(item);
			map[item.id] = item;
		});
		children.forEach((child) => {
			map[child.pid].children.push(child);
		});
		res.data = rootMenu;

		ctx.body = res;
	}
}

module.exports = Controller;
